package com.spzx.channel.configure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
//@SpringBootConfiguration
@Slf4j
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        //自定义线程池：7大参数
        //任务：
        // CPU 计算型       线程数：cpu + 1
        // IO 数据读写型     线程数：cpu * 2
        int availableProcessors = Runtime.getRuntime().availableProcessors(); //获取cpu数量  12
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                availableProcessors * 2,
                availableProcessors * 2,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(200),
                Executors.defaultThreadFactory(),
                (runnable, executor) -> {
                    log.error("线程池达到最大饱和，进行任务的拒绝策略。可以发短信、邮件、记录信息到数据库");
                }
        );

        //threadPoolExecutor.prestartCoreThread(); //只初始化一个核心线程
        threadPoolExecutor.prestartAllCoreThreads(); //初始化所有核心线程

        return threadPoolExecutor;
    }
}
